﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace work1
{
    class Serializer
    {
        public static string ObjectToString<T>(T t)         
        {
              BinaryFormatter formatter = new BinaryFormatter();
              using (MemoryStream stream = new MemoryStream())
              {                
                  formatter.Serialize(stream, t);
                  string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                  return result;
              }
        }
        public static void ObjectToFile<T>(T t, string path)
        {
              BinaryFormatter formatter = new BinaryFormatter();
              using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate))
              {                
                  formatter.Serialize(stream, t);
                  stream.Flush();
              }
        }

        public static T StringToObject<T>(string s) where T : class
        {
              byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s);
              BinaryFormatter formatter = new BinaryFormatter();
              using (MemoryStream stream = new MemoryStream(buffer))
              {
                  T result = formatter.Deserialize(stream) as T;
                  return result;
              }
        }
        public static T FileToObject<T>(string path) where T : class
        {
            using (FileStream stream = new FileStream(path, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                T result = formatter.Deserialize(stream) as T;
                return result;
            }
        }
    }
}
